Helper functions and macros that allow for easier testing of crates that use tracing
.
This crate should mainly be used through the #[traced_test]
macro.
Usage
First, add a dependency on tracing-test
in Cargo.toml
:
= { = "0.2", = ["rt-threaded", "macros"] }
= "0.1"
= "0.1"
Then, annotate your test function with the #[traced_test]
macro.
use ;
use traced_test;
async
Done! You can write assertions using the injected logs_contain
function. Logs
are written to stdout, so they are captured by the cargo test runner by
default, but printed if the test fails.
Of course, you can also annotate regular non-async tests:
use info;
use traced_test;
Rationale / Why You Need This
Tracing allows you to set a default subscriber within a scope:
# let subscriber = new;
# let req = 123;
#
let response = with_default;
This works fine, as long as no threads are involved. As soon as you use a
multi-threaded test runtime (e.g. the #[tokio::test]
with the rt-threaded
feature) and spawn tasks, the tracing logs in those tasks will not be captured
by the subscriber.
The macro provided in this crate registers a global default subscriber instead. This subscriber contains a writer which logs into a global static in-memory buffer.
At the beginning of every test, the macro injects span opening code. The span uses the name of the test function (unless it's already taken, then a counter is appended). This means that the logs from a test are prefixed with the test name, which helps when debugging.
Finally, a function called logs_contain(value: &str)
is injected into every
annotated test. It filters the logs in the buffer to include only lines
containing {span_name}:
and then searches the value in the matching log
lines. This can be used to assert that a message was logged during a test.